var canvas = document.getElementsByTagName("canvas")[0];

if (canvas != null) {
    chrome.runtime.sendMessage({ type: "init" });
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.type == 'click') {
        clickOn(request.x, request.y)
    }
});

function sendMessage(message, callback) {
    chrome.runtime.sendMessage(message, function (response) {
        if (callback) callback(response);
    });
}

function clickOn(x, y) {
    canvas.dispatchEvent(createPointerEvent("pointerdown", x, y));
    setTimeout(function () { canvas.dispatchEvent(createPointerEvent("pointerup", x, y)); }, 100);
}

function createPointerEvent(type, x, y) {
    var settings = {};
    settings.bubbles = true;
    settings.cancelable = true;
    settings.clientX = x;
    settings.clientY = y;
    settings.composed = true;
    settings.isPrimary = true;
    settings.isTrusted = true;
    settings.layerX = x;
    settings.layerY = y;
    settings.offsetX = x;
    settings.offsetY = y;
    settings.pointerId = 1;
    settings.pointerType = "mouse";
    settings.screenX = x;
    settings.screenY = y;
    settings.x = x;
    settings.y = y;

    var evt = new PointerEvent(type, settings);
    return evt;
}

var hiddenDiv = document.getElementById('KCEEventDiv');
if (!hiddenDiv) {
    hiddenDiv = document.createElement('div');
    hiddenDiv.id = 'KCEEventDiv';
    hiddenDiv.style.display = 'none';
    document.body.appendChild(hiddenDiv);
}
hiddenDiv.addEventListener('KCEEvent', function (e) {
    if (e.detail.type == "KCE_MSG") {
        sendMessage(e.detail);
    }
}, false);

function injectCustomJs(jsPath) {
    jsPath = jsPath || 'js/inject.js';
    var temp = document.createElement('script');
    temp.setAttribute('type', 'text/javascript');
    temp.src = chrome.extension.getURL(jsPath);
    temp.onload = function () {
        this.parentNode.removeChild(this);
    };
    document.head.appendChild(temp);
}

injectCustomJs("js/injected-script.js");